package net.aetherial.context.grounding.gatherers;

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;

/**
 * Collects conversational turns from a specialized XML file and passes the turns on to the rest of the system.
 */

public class XmlGatherer extends Gatherer
{

	/**
	 * Starts the thread that iterates through all chats located in the directory specified by the system property <code>xml.chats.path</code>. Processes
	 * each file and sends individual turns to the rest of the system.
	 */

	public void run() 
	{
		String path = System.getProperty ("xml.chats.path");

		if (path == null)
			path = "/Users/cjkarr/Desktop/coded_chats";

		try 
		{

			File f = new File (path);

			if (f.isDirectory ())
			{
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ();
				factory.setIgnoringElementContentWhitespace (true);
				
				DocumentBuilder builder = factory.newDocumentBuilder ();

				File[] children = f.listFiles ();

				for (File child: children)
				{
					if (child.getAbsolutePath().endsWith (".xml"))
					{
						Document d = builder.parse (child);
						
						NodeList list = d.getElementsByTagName ("turn");
						
						for (int i = 0; i < list.getLength (); i++)
						{
							Element turn = (Element) list.item (i);
							
							analyzer.process (turn.getAttribute ("sender"), turn.getTextContent (), Double.parseDouble (turn.getAttribute ("score")));
						}
						
						analyzer.reset ();
					}
				}
			}
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
}
